﻿using suirui.ZhuMu.Log;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace suirui.ZhuMu.Common
{
    public class EmailHelper
    {
        private const string SMTPHOST = "smtp2525.sendcloud.net";
        private const int SMTPPORT = 2525;
        public const string SUPPORTEMAIL = "support@zhumu.me";
        public const string NOREPLYEMAIL = "no-reply@zhumu.me";

        private const string API_USER = "zhumumail";
        private const string BatchSendAPI_USER = "batchSendUser";

        private const string API_KEY = "WY6W2R8pNSahqUkS";


        /// <summary>
        /// 发送邮件基础方法
        /// </summary>
        /// <param name="toAddr">发送地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <param name="fromEmail">发送地址</param>
        /// <param name="passwd">密码</param>
        /// <returns></returns>
        public static bool Send163Email(string toAddr, string title, string strBody, string fromEmail, string passwd)
        {

            try
            {
                MailMessage myMail = new MailMessage(); //创建邮件实例对象

                myMail.From = new MailAddress(fromEmail); //发送者，要和邮件服务器的验证信息对应，不能随便更改

                myMail.To.Add(new MailAddress(toAddr)); //接收者

                myMail.Subject = title; //邮件标题
                myMail.SubjectEncoding = Encoding.UTF8; //标题编码

                myMail.Body = strBody; //邮件内容
                myMail.BodyEncoding = Encoding.UTF8; //邮件内容编码
                myMail.IsBodyHtml = true;     //邮件内容是否支持html

                SmtpClient smtp = new SmtpClient(); //创建smtp实例对象
                smtp.Host = SMTPHOST; //邮件服务器SMTP
                smtp.Port = 25;                  //邮件服务器端口
                smtp.Credentials = new NetworkCredential(fromEmail, passwd); //邮件服务器验证信息

                smtp.Send(myMail); //发送邮件

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 发送邮件基础方法
        /// </summary>
        /// <param name="toAddr">发送地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <param name="fromEmail">发送地址</param>
        /// <param name="passwd">密码</param>
        /// <returns></returns>
        public static bool SendCloudEmail(string toAddr, string title, string strBody, string fromEmail, string file = "", string fileName = "")
        {
            return SendCloudEmail(toAddr, title, strBody, fromEmail, API_USER, API_KEY, file, fileName);
        }

        /// <summary>
        /// 发送邮件基础方法
        /// </summary>
        /// <param name="toAddr">发送地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <param name="fromEmail">发送地址</param>
        /// <param name="passwd">密码</param>
        /// <returns></returns>
        public static bool BatchSendCloudEmail(string toAddr, string title, string strBody, string fromEmail = "no-reply@zhumu.me")
        {
            return SendCloudEmail(toAddr, title, strBody, fromEmail, BatchSendAPI_USER, API_KEY, "", "");
        }
        /// <summary>
        /// 发送邮件基础方法
        /// </summary>
        /// <param name="toAddr">发送地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <param name="fromEmail">发送地址</param>
        /// <param name="passwd">密码</param>
        /// <returns></returns>
        public static bool SendCloudEmail(string toAddr, string title, string strBody, string fromEmail, string apiUser, string apiKey, string file, string fileName)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();
                var li = toAddr.Split(',');
                foreach (var item in li)
                {
                    // 收件人地址，用正确邮件地址替代
                    mailMsg.To.Add(new MailAddress(item));
                }

                // 发信人，用正确邮件地址替代
                mailMsg.From = new MailAddress(fromEmail, "瞩目团队");

                // 邮件主题
                mailMsg.Subject = title;

                // 邮件正文内容
                //string text = strBody;
                string html = strBody;
                //mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

                //添加附件
                if (!string.IsNullOrWhiteSpace(file))
                {
                    file = file.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "")
                    .Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");
                    byte[] arr = Convert.FromBase64String(file);
                    var f = new MemoryStream(arr);

                    Attachment data = new Attachment(f, fileName);
                    mailMsg.Attachments.Add(data);
                }

                ////实现“收到回执”功能
                //mailMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                //mailMsg.Headers.Add("ReturnReceipt", "1");
                //mailMsg.Headers.Add("Disposition - Notification - To", "returnreceipt@return.com");

                // 连接到sendcloud服务器
                SmtpClient smtpClient = new SmtpClient(SMTPHOST, SMTPPORT);
                // 使用api_user和api_key进行验证
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(apiUser, apiKey);
                smtpClient.Credentials = credentials;

                smtpClient.Send(mailMsg);
                DefaultLogFactory.Instance.Mail_Loger.Info(fromEmail + "发送到" + toAddr + "成功；" + " title=" + title);
                return true;
            }
            catch (Exception ex)
            {
                DefaultLogFactory.Instance.Mail_Loger.Error(fromEmail + "发送到" + toAddr + "失败:" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 发送注册邮件
        /// </summary>
        /// <param name="toAddr">发送地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="strBody">邮件内容</param>
        /// <returns></returns>
        public static bool SendRegisterEmail(string toAddr, string title, string strBody)
        {
            return SendCloudEmail(toAddr, title, strBody, NOREPLYEMAIL);
        }

        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="toAddr"></param>
        /// <param name="title"></param>
        /// <param name="strBody"></param>
        /// <returns></returns>
        public static bool SendEmail(string toAddr, string title, string strBody, string file, string fileName)
        {
            return SendCloudEmail(toAddr, title, strBody, NOREPLYEMAIL, file, fileName);
        }

        /// <summary>
        /// 客户通过主页发送联系邮件
        /// </summary>
        /// <param name="title"></param>
        /// <param name="strBody"></param>
        /// <returns></returns>
        public static bool SendSupportEmail(string toAddr, string title, string strBody)
        {
            return SendCloudEmail(SUPPORTEMAIL, title, strBody, toAddr);
        }

        /// <summary>
        /// 测试发送注册邮件
        /// </summary>
        public static void TestSendEmail()
        {
            string toAddr = "xiaowen_712@163.com";
            string title = "来自SendCloud的第一封邮件!";
            //string strBody = "你太棒了！你已成功的从SendCloud发送了一封测试邮件，接下来快登录前台去完善账户信息吧";

            StringBuilder data = new StringBuilder();
            data.Append("您好！\r\n <br />");
            data.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您的瞩目账户已创建，账号为您的电子邮件地址。\r\n <br />");
            data.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请点击以下链接激活账号：\r\n <br />");
            data.Append(string.Format("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href={0}>{1}</a>", "https://www.zhumu.me/User/Register?code=", "https://www.zhumu.me/User/Register?code=" + "\r\n<br/>"));
            data.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;如果上述链接无法点击，请黏贴以上链接到浏览器。（该链接30天内有效）\r\n<br />");
            data.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;点击上面的激活链接，表示已阅读并同意<a href='http://www.zhumu.me/TermsAndConditions.html'>使用条款</a>和<a href='http://www.zhumu.me/PrivacyPolicy.html'>隐私条款</a>。如果需要额外的帮助，请访问服务中心。\r\n<br />");
            data.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />");
            data.Append("感谢您对瞩目的支持，欢迎使用瞩目视频通信服务！<br />");

            data.Append("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br />");
            data.Append("请注意，本邮件由瞩目系统发出，该电子邮件地址不接受回复邮件。要解决问题或了解其他信息，请访问瞩目官网<a href='http://www.zhumu.me/index.html#services'> http://www.zhumu.me</a>或联系瞩目客服<br />");

            string strBody = data.ToString();

            bool result = SendRegisterEmail(toAddr, title, strBody);
        }
        public static bool SendAWSEmail(string toAddrs, string title, string strBody)
        {
            //try
            //{
            //    string AWSNOREPLYEMAIL = ConfigurationManager.AppSettings["AWSNOREPLYEMAIL"];//"servicebossplus@aptg.com.tw";
            //    string AWSHOST = ConfigurationManager.AppSettings["AWSHOST"];// "email-smtp.us-west-2.amazonaws.com";
            //    string AWSUSER = ConfigurationManager.AppSettings["AWSUSER"];// "AKIAIU4W7WXASZIPFTKA";
            //    string AWSPWD = ConfigurationManager.AppSettings["AWSPWD"];//"AoR+HNJHDKxAe7LWPYz3zuWe+5Z9EA7z8Y2+fXng4s4m";
            //    string AWSEmailName = ConfigurationManager.AppSettings["AWSEmailName"];//BOSS++

            //    MailMessage mailMsg = new MailMessage();

            //    // 收件人地址，用正确邮件地址替代
            //    //foreach (var toAddr in toAddrs)
            //    //{
            //    //    mailMsg.To.Add(new MailAddress(toAddr));
            //    //}
            //    mailMsg.To.Add(new MailAddress(toAddrs)); //接收者
            //    // 发信人，用正确邮件地址替代
            //    mailMsg.From = new MailAddress(AWSNOREPLYEMAIL, AWSEmailName);

            //    // 邮件主题
            //    mailMsg.Subject = title;

            //    // 邮件正文内容
            //    //string text = strBody;
            //    string html = strBody.Replace("\r\n", "<br />");
            //    //mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
            //    mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
            //    // 添加附件
            //    //string file = "C:\\file.pdf ";
            //    //Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            //    //mailMsg.Attachments.Add(data);

            //    // 连接到sendcloud服务器
            //    SmtpClient smtpClient = new SmtpClient(AWSHOST, 25);
            //    // 使用api_user和api_key进行验证
            //    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(AWSUSER, AWSPWD);
            //    smtpClient.Credentials = credentials;
            //    smtpClient.EnableSsl = true;
            //    smtpClient.Send(mailMsg);
            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    LogHelper.DefaultLoger.Error(new
            //    {
            //        Title = "SendAWSEmail",
            //        Exception = ex
            //    });
            return false;
            //}
        }

        public static bool SendRegisterEmailAWS(string toAddr, string title, string strBody)
        {
            return SendAWSEmail(toAddr, title, strBody);
        }
    }
}
